package com.mrper.ui.main;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.RotateAnimation;

import com.miguo.activity.fragment.IndexFragment;
import com.miguo.app.AppHelper;
import com.miguo.bean.CategoryBean;
import com.miguo.db.CategoryDB;
import com.miguo.ui.R;
import com.miguo.ui.databinding.FragmentHomeBinding;
import com.miguo.ui.databinding.GriditemChooseMenuBinding;
import com.miguo.utils.LongUtils;
import com.mrper.ext.adapter.fragment.SwitchFragmentStateAdapter;
import com.mrper.ext.annotation.ContentView;
import com.mrper.ext.dialog.ChooseMenuPopupWindow;
import com.mrper.ext.uibase.BasicFragment;
import com.mrper.util.ViewUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/8/22.
 * 新版首页
 */
@ContentView(R.layout.fragment_home)
public class FragmentHome extends BasicFragment<FragmentHomeBinding> implements ViewPager.OnPageChangeListener {

    public static final String TAG = FragmentBrandCategory.class.getSimpleName();

    private List<Fragment> fragments;//当前的fragment片段页面
    private ChooseMenuPopupWindow<CategoryBean> chooseMenuPopupWindow;//类型菜单窗口

    @Override
    protected void initViews() {
        super.initViews();
        dataBinder.setOnClickEvent(this);
        initTab(); //初始化Tab加载
    }

    //初始化Tab加载
    private void initTab() {
        final List<CategoryBean> categories = CategoryDB.getInstance(activity, true).findPid(LongUtils.StrToLong("0"));
//        Collections.sort(categories, new Comparator<CategoryBean>() {
//            @Override
//            public int compare(CategoryBean lhs, CategoryBean rhs) {
//                return (int)(lhs.getOrdid() - rhs.getOrdid()) ;
//            }
//        });
        categories.add(0, new CategoryBean(0L, "推荐", "", 0L, 0L));
        categories.add(1, new CategoryBean(1L, "最新", "", 0L, 0L));
        dataBinder.tabCategory.postDelayed(new Runnable() {
            @Override
            public void run() {
                initTabLayout(categories); //初始化TabLayout布局
                initChooseMenuWindow(categories); //初始化类型菜单
            }
        }, 100);
    }

    /**
     * 初始化TabLayout控件
     **/
    @SuppressWarnings({"unchecked","deprecation"})
    private void initTabLayout(List<CategoryBean> categories) {
        int dataSize = categories.size();
        fragments = new ArrayList<>();
        String[] titles = new String[dataSize];
        for (int index = 0; index < dataSize; index++) {
            //设置Tab标题
            String item = categories.get(index).getName();
            titles[index] = item; //记录标题
            dataBinder.tabCategory.addTab(dataBinder.tabCategory.newTab().setText(item), index == 0);
            //设置Tab的页面
            Fragment fragmentItem;
            if (index > 0) {
                Bundle argument = new Bundle();
                argument.putLong("cid", categories.get(index).getId());
                fragmentItem = ViewUtil.getFragmentInstance(FragmentHomeListContent.class, argument);
            } else {
                fragmentItem = ViewUtil.getFragmentInstance(IndexFragment.class, null);
            }
            fragments.add(fragmentItem);
        }
        if (Build.VERSION.SDK_INT >= 23) dataBinder.flContainer.addOnPageChangeListener(this);
        else dataBinder.flContainer.setOnPageChangeListener(this);
        dataBinder.flContainer.setAdapter(new SwitchFragmentStateAdapter(getChildFragmentManager(), fragments, titles));
        dataBinder.tabCategory.setupWithViewPager(dataBinder.flContainer);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
        if (position != 0) {
            FragmentHomeListContent fragment = (FragmentHomeListContent) fragments.get(position);
            fragment.initDataLoad();
        }
        setCurrentSelectedIndex(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.imgSignIn: //签到
                AppHelper.StartSign(activity);
                break;
            case R.id.btnSearch://搜索顶栏
                AppHelper.StartSearch(activity, dataBinder.txtSearch.getKeyword());
                break;
            case R.id.imgArrowDown:
                showChooseMenuWindow();//显示类型选择菜单
                break;
            default:
                break;
        }
    }


    /**
     * 初始化用户选择类型菜单
     **/
    private void initChooseMenuWindow(List<CategoryBean> types) {
        if (chooseMenuPopupWindow == null) {
            chooseMenuPopupWindow = new ChooseMenuPopupWindow<>(context, types, new ChooseMenuPopupWindow.OnInitItemListener<CategoryBean>() {
                @Override
                public void onInitItem(GriditemChooseMenuBinding binder, CategoryBean item, int position, int selectedIndex) {
                    binder.setIsSelected(position == selectedIndex);
                    binder.setName(item.getName());
                }
            }, new ChooseMenuPopupWindow.OnSelectedIndexChangedListener() {
                @Override
                public void onSelectedIndexChanged(int position) {
                    dataBinder.flContainer.setCurrentItem(position, true);
                }
            });
            chooseMenuPopupWindow.setOnVisibilityChangedListener(new ChooseMenuPopupWindow.OnVisibilityChangedListener() {
                @Override
                public void onVisibilityChanged(boolean isShow) {
                    RotateAnimation rotateAnimation = getRotateAnimation(isShow);
                    dataBinder.imgArrowDown.startAnimation(rotateAnimation);
                }

                @NonNull
                private RotateAnimation getRotateAnimation(boolean isShow) {
                    RotateAnimation rotateAnimation = new RotateAnimation(isShow ? 0 : 180, isShow ? 180 : 0,
                            RotateAnimation.RELATIVE_TO_SELF, 0.5F, RotateAnimation.RELATIVE_TO_SELF, 0.5f);
                    rotateAnimation.setDuration(150);
                    rotateAnimation.setInterpolator(new AccelerateInterpolator());
                    rotateAnimation.setFillAfter(true);
                    return rotateAnimation;
                }
            });
        }
    }

    /**
     * 设置当前的索引项
     **/
    private void setCurrentSelectedIndex(int index) {
        if (chooseMenuPopupWindow != null)
            chooseMenuPopupWindow.setSelectedIndex(index);
    }

    /**
     * 显示用户类型化菜单
     **/
    private void showChooseMenuWindow() {
        if (chooseMenuPopupWindow != null) {
            int[] locations = new int[2];
            dataBinder.tabContainer.getLocationOnScreen(locations);
            chooseMenuPopupWindow.setMenuGridLocation(0, locations[1] + dataBinder.tabContainer.getHeight()
                    + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? - statusBarHeight : 0));
            chooseMenuPopupWindow.showAtLocation(dataBinder.tabContainer, Gravity.TOP, 0, 0);
        }
    }

}
